/*
 * @(#)MaintContactPersonAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.contact.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.dcivision.contact.bean.ContactPerson;
import com.dcivision.contact.dao.ContactPersonDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.MessageResourcesFactory;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.AbstractMaintAction;

/**
  MaintContactPersonAction.java

  This class is for maint contact person.

    @author          Jenny Li
    @company         DCIVision Limited
    @creation date   29/08/2005
    @version         $Revision: 1.6.2.1 $
*/

public class MaintImportContactAction extends AbstractMaintAction {

  public static final String REVISION = "$Revision: 1.6.2.1 $";
  protected final static String MESSAGE_IMPORT_SUCCESS = "common.message.import_success";
  protected final static String ERROR_IMPORT_FAIL="error.contact.import_fail";

  public MaintImportContactAction() {
    super();
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return("com.dcivision.contact.dao.ContactPersonDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return(SystemFunctionConstant.CONTACT_PERSON);
  }
  
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    AbstractActionForm maintForm = (AbstractActionForm)form;

    String opMode = (maintForm!=null) ? maintForm.getOpMode() : request.getParameter("opMode");    //maintForm.getOpMode();
    String navMode = (maintForm!=null) ? maintForm.getNavMode() : request.getParameter("navMode"); //maintForm.getNavMode();
    log.debug( ((maintForm!=null) ? maintForm.getClass().getName() : "")+", OP Mode:"+opMode+", Nav Mode:"+navMode);

    // Set the function code for current action.
    ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
    if (forward!=null) {
      return forward;
    }

    try {
      if (GlobalConstant.OP_MODE_INSERT.equals(opMode)) {
        // Insert operation.
        try {
          this.insertRecord(mapping, maintForm, request, response);
          this.handleWorkflowRoutine(mapping, maintForm, request, response, opMode, navMode);
          this.commit(request);
          addMessage(request, MESSAGE_IMPORT_SUCCESS);
        } catch (ApplicationException appEx) {
          this.rollback(request);
          handleApplicationException(request, appEx);
        }
        if (isError(request)) {
          maintForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
          return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
        } else {
          maintForm.setNavMode(GlobalConstant.NAV_MODE_VIEW);
          return mapping.findForward(GlobalConstant.NAV_MODE_VIEW);
        }
      } else if (GlobalConstant.OP_MODE_INSERT_NEW.equals(opMode)) {
        // Insert and New operation.
        try {
          this.insertRecord(mapping, maintForm, request, response);
          this.handleWorkflowRoutine(mapping, maintForm, request, response, opMode, navMode);
          this.commit(request);
          form.reset(mapping, request);
          this.init(mapping, maintForm, request, response);
          addMessage(request, MESSAGE_IMPORT_SUCCESS);
        } catch (ApplicationException appEx) {
          this.rollback(request);
          handleApplicationException(request, appEx);
        }
        if (isError(request)) {
          maintForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
          return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
        } else {
          maintForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
          return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
        }
      } else {
        return super.execute(mapping,form,request,response);
      }
    } catch (ApplicationException ex) {
      handleApplicationException(request, ex);
      return mapping.findForward(GlobalConstant.NAV_MODE_LIST);
    }
  }
    
  public void insertRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    SessionContainer sessionContainer=this.getSessionContainer(request);
    Connection conn=this.getConnection(request);
    MaintContactPersonForm maintForm=(MaintContactPersonForm)form;
    ContactPersonDAObject contactPersonDAO=new ContactPersonDAObject(sessionContainer,conn);
    FormFile formFile=null;
    InputStream inputStream=null;
    String lineStr;
    ContactPerson contactPerson=new ContactPerson();
    try {
      formFile = maintForm.getUploadFile();
      if (formFile !=null) {
        inputStream = formFile.getInputStream();
      }
      if(formFile.getFileName().indexOf(".csv")>=0){
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String firstLineStr = reader.readLine();
        String[] StriUU=TextUtility.splitString(firstLineStr+",",",");
        while (firstLineStr != null) {
          lineStr=reader.readLine();  
          if(lineStr!=null){
            String[] lineStrUU=TextUtility.splitString(lineStr+",",",");
            for(int i=0;i<StriUU.length;i++){
              if(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "contact.label.import_first_name").equals(StriUU[i])){
                contactPerson.setFirstName(lineStrUU[i]);
              }else if(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "contact.label.last_name").equals(StriUU[i])){
                contactPerson.setLastName(lineStrUU[i]);
              }else if(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "contact.label.business_phone").equals(StriUU[i])){
                contactPerson.setPhoneNo(lineStrUU[i]);
              }else if(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "contact.label.mobile_phone").equals(StriUU[i])){
                contactPerson.setMobileNo(lineStrUU[i]);
              }else if(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "contact.label.business_fax").equals(StriUU[i])){
                contactPerson.setFaxNo(lineStrUU[i]);
              }else if(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "contact.label.email_address").equals(StriUU[i])){
                contactPerson.setEmail(lineStrUU[i]);
              }else if(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "contact.label.notes").equals(StriUU[i])){
                contactPerson.setRemarks(lineStrUU[i]);
              }else if(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "contact.label.job_title").equals(StriUU[i])){
                contactPerson.setTitle(lineStrUU[i]);
              }else if(MessageResourcesFactory.getMessage(sessionContainer.getSessionLocale(), "contact.label.department").equals(StriUU[i])){
                contactPerson.setDepartment(lineStrUU[i]);
              }           
            }
            contactPerson.setOwnerID(sessionContainer.getUserRecordID());
            contactPerson.setPublicFlag(maintForm.getPublicFlag());
            if(Utility.isEmpty(contactPerson.getFirstName()) || Utility.isEmpty(contactPerson.getLastName()) || Utility.isEmpty(contactPerson.getEmail())){
              throw new ApplicationException(ERROR_IMPORT_FAIL);
            }
            contactPersonDAO.insertObject(contactPerson);
          }else {
            break;
          }
        }
      }else{
        throw new ApplicationException(ERROR_IMPORT_FAIL);
      }
    } catch (IOException ee) {
      log.error(ee, ee);
    }
    
  }

}